<?php

namespace bc\model;

use bc\ar\MActiveRecord;

class OrderModel extends MActiveRecord
{
	
	public $autoId = 'order_id';
	const PRODUCT_ID = 1;
	
	/**
	 * 
	 */
	public static function tableName()
	{
		return '{{%order}}';
	}

	/**
	 *
	 * @param array $params
	 * @param integer $page
	 * @param integer $pageSize
	 */
	public function getList($params, $page = null, $pageSize = null)
	{

		$ar = $this->find ()->select($this->columns)
			->leftJoin('bc_order_detail', 'bc_order.order_id = bc_order_detail.order_id')
			->leftJoin('bc_product', 'bc_product.product_id = bc_order_detail.product_id')
			->leftJoin('bc_order_address', 'bc_order_address.id = bc_order.address_id')
			->leftJoin('ecs_users', 'bc_order.user_id = ecs_users.user_id')
			->leftJoin('bc_wx_user', 'bc_wx_user.openid = ecs_users.wxid')
			->leftJoin('bc_order_status', 'bc_order_status.order_status_id = bc_order.order_status')
			->where($params);
		if ($page && $pageSize)
		{
			$offset = $this->getOffset ( $page, $pageSize );
			$ar->offset($offset)->limit($pageSize);
		}

		if($this->sort == null)
			$ar->orderBy ( $this->autoId . ' DESC' );
		else
			$ar->orderBy ( $this->sort );
//		echo $ar->createCommand()->getRawSql();
		return $ar->asArray()->all();
	}

	/**
	 *
	 * @param array $params
	 */
	public function getRowOne($params = array())
	{
		$row = self::findOne($params);
		if($row)
			return $row->toArray();

		return null;
	}

	public function getRow($params = array())
	{
		if($this->columns == '*') {
			$this->columns = 'bc_order_detail.*,bc_product.*,bc_order.*,bc_order_address.*,bc_wx_user.*,ecs_users.*,bc_order_status.*,bc_order.create_time as ocreate_time,bc_order.order_no as oorder_no,bc_order.pay_time as opay_time,bc_order.send_time as osend_time,bc_order.pay_status as opay_status,bc_order.order_status as oorder_status,bc_order_address.city as city_name,bc_order_address.province as province_name,bc_order_address.district as district_name,bc_order_address.address as address_name,bc_wx_user.nickname as wnickname';
		}
		$row = $this->find()->select($this->columns)
			->leftJoin('bc_order_detail', 'bc_order.order_id = bc_order_detail.order_id')
			->leftJoin('bc_product', 'bc_product.product_id = bc_order_detail.product_id')
			->leftJoin('bc_order_address', 'bc_order_address.id = bc_order.address_id')
                        ->leftJoin('ecs_users', 'bc_order.user_id = ecs_users.user_id')
			->leftJoin('bc_wx_user', 'bc_wx_user.openid = ecs_users.wxid')
			->leftJoin('bc_order_bind', 'bc_order_bind.order_id = bc_order.order_id')
			->leftJoin('bc_product_sample', 'bc_product.product_id = bc_product_sample.product_id')
			->leftJoin('bc_order_status', 'bc_order_status.order_status_id = bc_order.order_status')->where($params);
		
		if($row)
			return $row->asArray()->all();
			
		return null;
	}
	
	
	/**
	 * 
	 * @param array|string $params
	 * @return array
	 */
	public function getInfoByFrontend($params)
	{
		
		$ar = $this->find()->select($this->columns)
				->leftJoin('bc_order_detail', 'bc_order.order_id = bc_order_detail.order_id')
				->leftJoin('bc_product', 'bc_product.product_id = bc_order_detail.product_id');
		if($params)
			$ar->where($params);
		return $ar->asArray()->all();
	}
	

	/**
	 *
	 * @param array $condition
	 * @return integer
	 */
	public function getTotal($condition='1=1')
	{
		if(!empty($condition))
			return $this->find()
				->leftJoin('bc_order_detail', 'bc_order.order_id = bc_order_detail.order_id')
                                ->leftJoin('bc_product', 'bc_product.product_id = bc_order_detail.product_id')
				->leftJoin('ecs_users', 'bc_order.user_id = ecs_users.user_id')
				->leftJoin('bc_order_address', 'bc_order_address.id = bc_order.address_id')
				->leftJoin('bc_wx_user', 'bc_wx_user.id = bc_order.user_id')
				->where($condition)->count();
		else
			return 0;
	}

	/*
	 * 获取用户是否有购买过此商品，但是没付款的
	 * */
	public function checkBuyProduct($user_id,$product_id)
	{
		$ar = $this->find()->innerJoin('bc_order_detail', 'bc_order.order_id = bc_order_detail.order_id')->where(['bc_order.user_id'=>$user_id,'bc_order_detail.product_id'=>$product_id,'bc_order.pay_status'=>0]);
		return $ar->one();
	}

	/**
	 *
	 * @param array|string $params
	 * @return array
	 */
	public function getOrderListByFrontend($params)
	{

		$ar = $this->find()->select($this->columns)
			->leftJoin('bc_order_bind', 'bc_order.order_id = bc_order_bind.order_id')
			->leftJoin('bc_order_detail', 'bc_order.order_id = bc_order_detail.order_id')
			->leftJoin('bc_product', 'bc_product.product_id = bc_order_detail.product_id')
			->leftJoin('bc_product_sample', 'bc_product.product_id = bc_product_sample.product_id')
			->leftJoin('bc_order_status', 'bc_order_status.order_status_id = bc_order.order_status');
		if($params)
			$ar->where($params);
//		echo $ar->createCommand()->getRawSql();
//		die();
		return $ar->asArray()->all();
	}

	public function getEnvUrl()
	{
		if(YII_ENV == 'prod'){
			$view['shop_order']='http://wx.zhishimama.com/shop/mobile/user.php?act=order_list';
			$view['f_order']='http://wx.zhishimama.com/sale/order/orderlist';
		}else{
			$view['shop_order']='http://test.wx.zhishimama.com/shop/mobile/user.php?act=order_list';
			$view['f_order']='http://test.wx.zhishimama.com/sale/order/orderlist';
		}

		return $view;
	}

	public function dataHandling($DataArr)
	{
		if(!is_array($DataArr)){
			return array();
		}

		//数据处理
		$orderListArr=array();
		$viewData=array();
		foreach($DataArr as $key => $value)
		{
			if (in_array($value['border_id'], $orderListArr)) {
				if(empty($value['user_id'])) {
					$viewData[$value['border_id']]['sample_status_0'] = 1;
				}else{
					$viewData[$value['border_id']]['sample_status_1'] = 1;
				}
				continue;
			}

			$orderListArr[]=$value['border_id'];
			if(empty($value['user_id'])) {
				$value['sample_status_0'] = 1;
				$value['sample_status_1'] = 0;
				$viewData[$value['border_id']] = $value;
			}else{
				$value['sample_status_0'] = 0;
				$value['sample_status_1'] = 1;
				$viewData[$value['border_id']] = $value;
			}
		}

		return $viewData;
	}

	//到处$objPHPExcel = new \PHPExcel();
	public function excel($list)
	{
		$objPHPExcel = new \PHPExcel();

		$filename = '订单列表导出';
		// Set properties
		$objPHPExcel->getProperties()->setCreator("ctos")
			->setLastModifiedBy("ctos")
			->setTitle("Office 2007 XLSX Test Document")
			->setSubject("Office 2007 XLSX Test Document")
			->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
			->setKeywords("office 2007 openxml php")
			->setCategory("Test result file");

		// set width
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(13);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(3);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(5);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(8);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(13);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(40);
		$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(8);

		// 设置行高度
//        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);
//        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);

		// 字体和样式
//        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
//        $objPHPExcel->getActiveSheet()->getStyle('A2:D2')->getFont()->setBold(true);
//        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
//
//        $objPHPExcel->getActiveSheet()->getStyle('A2:D2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//        $objPHPExcel->getActiveSheet()->getStyle('A2:D2')->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
//
//        // 设置水平居中
		$objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('I')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('J')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('K')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		//  合并
//        $objPHPExcel->getActiveSheet()->mergeCells('A1:D1');

		// 表头
		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', '订单号')
			->setCellValue('B1', '下单时间')
			->setCellValue('C1', '支付时间')
			->setCellValue('D1', '购买人手机号')
			->setCellValue('E1', '昵称')
			->setCellValue('F1', '购买份数')
			->setCellValue('G1', '金额')
			->setCellValue('H1', '收货人名')
			->setCellValue('I1', '收货人电话')
			->setCellValue('J1', '收货地址')
			->setCellValue('K1', '订单状态');

		// 内容
		for ($i = 0, $len = count($list); $i < $len; $i++) {
			$objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($i + 2), $list[$i]['order_no'], \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($i + 2), empty($list[$i]['ocreate_time']) ? '':date('Y-m-d G:i:s',$list[$i]['ocreate_time']), \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($i + 2), empty($list[$i]['opay_time']) ? '':date('Y-m-d G:i:s',$list[$i]['opay_time']), \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('D' . ($i + 2), $list[$i]['mobile'], \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('E' . ($i + 2), $list[$i]['nickname'], \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('F' . ($i + 2), $list[$i]['product_num'], \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('G' . ($i + 2), $list[$i]['oorder_amount'], \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('H' . ($i + 2), $list[$i]['addressee_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('I' . ($i + 2), $list[$i]['add_telephone'], \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('J' . ($i + 2), $list[$i]['province_name'].$list[$i]['city_name'].$list[$i]['district_name'].$list[$i]['address_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
			$objPHPExcel->getActiveSheet(0)->setCellValue('K' . ($i + 2), $list[$i]['order_status_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
		}

		// Rename sheet
//        $objPHPExcel->getActiveSheet()->setTitle("订单列表");

		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);
		// 输出
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="' . $filename. date('Y-m-d G:i:s',time()) . '.xls"');
		header('Cache-Control: max-age=0');
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
	}
	
	
	/**
	 * 判断用户商品是否首次购买
	 * @param int $productId
	 * @param int $userId
	 */
	public function firstBuy($productId, $userId)
	{
		$ar = $this->find ()->select($this->columns)
			->leftJoin('bc_order_detail', 'bc_order.order_id = bc_order_detail.order_id')
			->where(['product_id' => (int)$productId, 'user_id' => $userId]);
		return $ar->one();
	}
}

